<?php

/**
 * Categories model
 * 
 * @author    Kanat Gailimov, http://gailimov.info
 * @copyright Copyright (c) Kanat Gailimov (http://gailimov.info) 2011
 */

class Application_Model_DbTable_Categories extends Zend_Db_Table_Abstract
{
    /**
     * DB table name
     * 
     * @var string
     */
    protected $_name = 'zf_categories';

    /**
     * Get by ID
     * 
     * @param  int   $id ID
     * @return array
     */
    public function getById($id)
    {
        $id = intval($id);
        $row = $this->fetchRow('id = ' . $id);
        if (!$row) {
            throw new Exception('Ошибка! Выборка данных по категории не прошла!');
        }
        return $row;
    }

    public function getAllCategories()
    {
        $select = $this->fetchAll();
        return $select;
    }

    public function getParentCategories()
    {
        $select = $this->fetchAll();
        $list = array();
        foreach($select as $parentCat) {
            $key = $parentCat->id;
            $list[$key] = $parentCat->title;
        }
        return $list;
    }

    public function setCount($id, $delta)
    {

    }
    /**
     * Add category
     *
     * @param  string $name    Name of category
     * @param  string $url     URL of category
     * @return bool
     */
    public function add($catName, $catUrl, $parentCat)
    {
        $data = array(
            'title' => $catName,
            'url' => $catUrl,
            'parent_id' => $parentCat,
        );
        $this->insert($data);
    }

    public function edit($id, $catName, $catUrl, $parentCat)
    {
        if ($id == $parentCat) {
            return FALSE;
        }
        $data = array(
            'title' => $catName,
            'url' => $catUrl,
            'parent_id' => $parentCat,
        );
        $this->update($data, 'id =' . $id);
        return TRUE;
    }

    public function deleteCategory($id)
    {
        $result = FALSE;
        $this->fetchRow('id = ' . $id);
        if ($id == 1) {
            $result = FALSE;
        } else {
            $this->delete('id = ' . $id);
        }
        return $result;
    }
}